<html>

<head>
  <title>离线瓦片地图</title>
  <link rel="stylesheet" type="text/css" href="./ol.css">
  <script type="text/javascript" src="./ol.js" charset="utf-8"></script>

  <style>
    .map {
      width: 100%;
      height: 400px;
    }

    .ol-tooltip {
      position: relative;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 4px;
      color: white;
      padding: 4px 8px;
      opacity: 0.7;
      white-space: nowrap;
      font-size: 12px;
      cursor: default;
      user-select: none;
    }

    .ol-tooltip-measure {
      opacity: 1;
      font-weight: bold;
    }

    .ol-tooltip-static {
      background-color: #ffcc33;
      color: black;
      border: 1px solid white;
    }

    .ol-tooltip-measure:before,
    .ol-tooltip-static:before {
      border-top: 6px solid rgba(0, 0, 0, 0.5);
      border-right: 6px solid transparent;
      border-left: 6px solid transparent;
      content: "";
      position: absolute;
      bottom: -6px;
      margin-left: -7px;
      left: 50%;
    }

    .ol-tooltip-static:before {
      border-top-color: #ffcc33;
    }
  </style>
</head>

<body>
  <div id="map" class="map"></div>
  <form class="form-inline">
    <label for="type">Measurement type &nbsp;</label>
    <select id="type">
      <option value="length">Length (LineString)</option>
      <option value="area">Area (Polygon)</option>
    </select>
  </form>

  <script type="text/javascript">



    // 地图设置中心，设置到成都，在本地离线地图 offlineMapTiles刚好有一张zoom为4的成都瓦片
    var center = ol.proj.transform([104.06667, 30.66667], 'EPSG:4326', 'EPSG:3857');
    //var center = ol.proj.transform([104.06667, 30.66667], 'EPSG:4326', 'EPSG:3857');
    //创建地图
    var map = new ol.Map({
      view: new ol.View({
        center: center,
        projection: 'EPSG:3857',
        zoom: 7,
        maxZoom: 14,
        minZoom: 4
      }),
      target: 'map'
    });

    function zeroFill(num, len, radix) {
      var str = num.toString(radix || 10);
      while (str.length < len) {
        str = "0" + str;
      }
      return str;
    }
    // 添加一个使用离线瓦片地图的层
    var offlineMapLayer = new ol.layer.Tile({
      source: new ol.source.XYZ({
        url: 'http://localhost:8080/gis/{z}/{x}/{y}.png'
        // url: 'http://localhost:8080/GoogleDX/{z}/{x}/{y}.png'
      })
    });
    map.addLayer(offlineMapLayer);






    /**
 * Currently drawn feature.
 * @type {import("../src/ol/Feature.js").default}
 */
    let sketch;

    /**
     * The help tooltip element.
     * @type {HTMLElement}
     */
    let helpTooltipElement;

    /**
     * Overlay to show the help messages.
     * @type {Overlay}
     */
    let helpTooltip;
    /**
     * Message to show when the user is drawing a line.
     * @type {string}
     */
    const continueLineMsg = '点击继续画线';


    /**
 * Handle pointer move.
 * @param {import("../src/ol/MapBrowserEvent").default} evt The event.
 * 鼠标移动事件监听
 */
    const pointerMoveHandler = function (evt) {
      if (evt.dragging) {
        return;
      }
      /** @type {string} */
      let helpMsg = '点击开始绘制';

      if (sketch) {
        const geom = sketch.getGeometry();
        if (geom instanceof ol.geom.LineString) {
          helpMsg = continueLineMsg;
        }
      }

      helpTooltipElement.innerHTML = helpMsg;
      helpTooltip.setPosition(evt.coordinate);

      helpTooltipElement.classList.remove('hidden');
    };

    map.on('pointermove', pointerMoveHandler);
    map.getViewport().addEventListener('mouseout', function () {
      helpTooltipElement.classList.add('hidden');
    });

    const typeSelect = document.getElementById('type');

    let draw; // global so we can remove it later

    /**
     * Format length output.
     * @param {LineString} line The line.
     * @return {string} The formatted length.
     * 用于转换米千米
     */
    const formatLength = function (line) {
      const length = ol.sphere.getLength(line);
      let output;
      if (length > 100) {
        output = Math.round((length / 1000) * 100) / 100 + ' ' + 'km';
      } else {
        output = Math.round(length * 100) / 100 + ' ' + 'm';
      }
      return output;
    };

    function addInteraction() {
      console.log("执行了")


      const source = new ol.source.Vector();
      const vector = new ol.layer.Vector({
        source: source,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)',
          }),
          stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 2,
          }),
          image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill({
              color: '#ffcc33',
            }),
          }),
        }),
      });
      map.addLayer(vector);

      // const type = typeSelect.value == 'area' ? 'Polygon' : 'LineString';
      draw = new ol.interaction.Draw({
        source: source,
        // type: type,
        type: "LineString",
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)',
          }),
          stroke: new ol.style.Stroke({
            color: 'rgba(0, 0, 0, 0.5)',
            lineDash: [10, 10],
            width: 2,
          }),
          image: new ol.style.Circle({
            radius: 5,
            stroke: new ol.style.Stroke({
              color: 'rgba(0, 0, 0, 0.7)',
            }),
            fill: new ol.style.Fill({
              color: 'rgba(255, 255, 255, 0.2)',
            }),
          }),
        }),
      });
      map.addInteraction(draw);
      let data = createMeasureTooltip();
      let measureTooltip = data[0]
      let measureTooltipElement = data[1]

      // let measureClose = createMeasureClose(vector, measureTooltip);
      let data2 = createMeasureClose(vector, measureTooltip);
      let measureClose = data2[0]
      let measureCloseElement = data2[1]
      createHelpTooltip();
      let listener;
      draw.on('drawstart', function (evt) {
        // set sketch
        sketch = evt.feature;

        /** @type {import("../src/ol/coordinate.js").Coordinate|undefined} */
        let tooltipCoord = evt.coordinate;

        listener = sketch.getGeometry().on('change', function (evt) {
          const geom = evt.target;
          let output;
          if (geom instanceof ol.geom.LineString) {
            output = formatLength(geom);
            tooltipCoord = geom.getLastCoordinate();
          }
          console.log(output)
          measureTooltipElement.innerHTML = output;
          measureTooltip.setPosition(tooltipCoord);
          measureClose.setPosition(tooltipCoord);
        });
        console.log("开始画了")


      });

      draw.on('drawend', function () {
        measureTooltipElement.className = 'ol-tooltip ol-tooltip-static';
        measureTooltip.setOffset([0, -7]);
        measureCloseElement.className = 'ol-tooltip ol-tooltip-static';
        measureClose.setOffset([-56, -9]);
        // unset sketch
        sketch = null;
        // unset tooltip so that a new one can be created

        // measureTooltipElement = null;
        // measureCloseElement = null;
        ol.Observable.unByKey(listener);
        console.log("画结束了")
        map.removeInteraction(draw);
        map.removeOverlay(helpTooltip);
      });
    }


    /**
 * Creates a new help tooltip
 */
    function createHelpTooltip() {
      if (helpTooltipElement) {
        helpTooltipElement.parentNode.removeChild(helpTooltipElement);
      }
      helpTooltipElement = document.createElement('div');
      helpTooltipElement.className = 'ol-tooltip hidden';
      helpTooltip = new ol.Overlay({
        element: helpTooltipElement,
        offset: [15, 0],
        positioning: 'center-left',
      });
      map.addOverlay(helpTooltip);
    }

    /**
 * Creates a new measure tooltip
 */
    function createMeasureTooltip() {
      let measureTooltip = null;
      let measureTooltipElement = null;
      if (measureTooltipElement) {
        measureTooltipElement.parentNode.removeChild(measureTooltipElement);
      }
      measureTooltipElement = document.createElement('div');
      measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure';
      measureTooltip = new ol.Overlay({
        element: measureTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
        stopEvent: false,
        insertFirst: false,
      });
      map.addOverlay(measureTooltip);
      return [measureTooltip, measureTooltipElement];
    }
    /**
* Creates a new measure close
*/
    function createMeasureClose(vector, measureTooltip) {
      let measureClose = null;
      let measureCloseElement = null;
      if (measureCloseElement) {
        measureCloseElement.parentNode.removeChild(measureCloseElement);
      }
      measureCloseElement = document.createElement('a');
      measureCloseElement.innerHTML = "关闭";
      measureCloseElement.title = "清除测量";
      measureCloseElement.className = 'ol-tooltip ol-tooltip-measure';
      measureCloseElement.style.cursor = 'pointer';

      measureCloseElement.addEventListener("click", () => {
        map.removeOverlay(measureTooltip);
        map.removeOverlay(measureClose);
        map.removeLayer(vector);
        console.log("点击了删除")
      });
      measureClose = new ol.Overlay({
        element: measureCloseElement,
        offset: [-56, -17],
        positioning: 'bottom-center',
        stopEvent: false,
        insertFirst: false,
      });
      map.addOverlay(measureClose);
      return [measureClose, measureCloseElement];
    }

    /**
     * Let user change the geometry type.
     */
    typeSelect.onchange = function () {
      addInteraction();
    };
    addInteraction();
  </script>

</body>

</html>